package com.dy.yandi.biz.service.requirement;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dy.yandi.api.client.requirement.model.DesignRequirement;
import com.dy.yandi.api.client.requirement.model.DesignRequirementHistory;
import com.dy.yandi.api.client.requirement.model.DesignRequirementProducer;
import com.dy.yandi.api.client.requirement.model.dto.DesignRequirementDto;
import com.dy.yandi.api.client.requirement.model.vo.DesignMaterialVo;
import com.dy.yandi.api.client.requirement.model.vo.DesignRequirementProducerVo;
import com.dy.yandi.api.client.requirement.model.vo.DesignRequirementVo;
import com.dy.yandi.api.client.requirement.service.DesignRequirementService;
import com.dy.yandi.api.constant.Constants;
import com.dy.yandi.api.enums.DesignEnum;
import com.dy.yandi.api.enums.DesignFileTypeEnum;
import com.dy.yandi.biz.component.bean.YandiProperties;
import com.dy.yandi.biz.dao.pig.AdLabelRelateMapper;
import com.dy.yandi.biz.dao.pig.DesignRequirementHistoryMapper;
import com.dy.yandi.biz.dao.pig.DesignRequirementMapper;
import com.dy.yandi.biz.dao.pig.DesignRequirementProducerMapper;
import com.dy.yandi.biz.service.DataChartService;
import com.dy.yunying.api.entity.ParentGameDO;
import com.dy.yunying.api.feign.RemotePGameService;
import com.dy.yunying.api.req.ParentGameReq;
import com.pig4cloud.pig.api.entity.AdLabelRelate;
import com.pig4cloud.pig.api.entity.AdMaterial;
import com.pig4cloud.pig.api.feign.RemoteAdMaterialService;
import com.pig4cloud.pig.api.util.Page;
import com.pig4cloud.pig.api.util.UploadUtils;
import com.pig4cloud.pig.api.vo.AdMaterialVo;
import com.pig4cloud.pig.common.core.constant.SecurityConstants;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.minio.service.MinioTemplate;
import com.pig4cloud.pig.common.security.tenant.TenantContextHolder;
import com.pig4cloud.pig.common.security.util.SecurityUtils;
import com.sjda.framework.common.utils.DateUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 需求表
 * @author  chengang
 * @version  2021-09-28 13:44:24
 * table: design_requirement
 */
@Log4j2
@Service
@RequiredArgsConstructor
public class DesignRequirementServiceImpl extends ServiceImpl<DesignRequirementMapper, DesignRequirement> implements DesignRequirementService {

	private final DesignRequirementMapper designRequirementMapper;
	private final DesignRequirementHistoryMapper designRequirementHistoryMapper;
	private final DesignRequirementProducerMapper designRequirementProducerMapper;
	private final AdLabelRelateMapper adLabelRelateMapper;
	private final DataChartService dataChartService;
	private final MinioTemplate minioTemplate;
	private final YandiProperties yandiProperties;
	private final RemotePGameService remotePGameService;
	private final RemoteAdMaterialService remoteAdMaterialService;

	/**
	 * 需求列表 - 分页
	 * @param vo
	 * @return
	 */
	@Override
	public R getPage(DesignRequirementVo vo){
		vo.setTenantId(String.valueOf(TenantContextHolder.getTenantId()));
		IPage<DesignRequirementDto> iPage = designRequirementMapper.selectRequirementByPage(vo);
		// 处理结果
		dealData(iPage.getRecords());
		return R.ok(iPage);
	}
	/**
	 * 我的需求 - 分页
	 * @param vo
	 * @return
	 */
	@Override
	public R getMyNeedPage(DesignRequirementVo vo){
		vo.setUserId(String.valueOf(SecurityUtils.getUser().getId()));
		vo.setTenantId(String.valueOf(TenantContextHolder.getTenantId()));
		IPage<DesignRequirementDto> iPage = designRequirementMapper.selectRequirementByPage(vo);
		// 处理结果
		dealData(iPage.getRecords());
		return R.ok(iPage);
	}
	/**
	 * 已完成 - 分页
	 * @param vo
	 * @return
	 */
	@Override
	public R getComplete(DesignRequirementVo vo){
		boolean isManager = dataChartService.isDesignManager();
		if (!isManager){
			if (StringUtils.isBlank(vo.getProducerId()) || StringUtils.equals(String.valueOf(SecurityUtils.getUser().getId()), vo.getProducerId())) {
				vo.setProducerId(String.valueOf(SecurityUtils.getUser().getId()));
			} else {
				IPage<DesignRequirementDto> iPage = new Page<>();
				return R.ok(iPage);
			}
		}
		vo.setStatus("5");
		vo.setTenantId(String.valueOf(TenantContextHolder.getTenantId()));
		IPage<DesignRequirementDto> iPage = designRequirementMapper.selectRequirementByPage(vo);
		// 处理结果
		dealData(iPage.getRecords());
		return R.ok(iPage);
	}
	/**
	 * 待审核 - 分页
	 * @param vo
	 * @return
	 */
	@Override
	public R getAudit(DesignRequirementVo vo){
		boolean isManager = dataChartService.isDesignManager();
		if (!isManager){
			IPage<DesignRequirementDto> iPage1 = new Page<>();
			return R.ok(iPage1);
		}
		vo.setTenantId(String.valueOf(TenantContextHolder.getTenantId()));
		IPage<DesignRequirementDto> iPage = designRequirementMapper.selectRequirementByPage(vo);
		// 处理结果
		dealData(iPage.getRecords());
		return R.ok(iPage);
	}
	/**
	 * 发布需求
	 * @param vo
	 * @return
	 */
	@Override
	public R addEditNeed(DesignRequirementVo vo){
		DesignRequirement requirement = new DesignRequirement();
		requirement.setType(DesignEnum.DESIGN_TYPE_1.getKey());
		requirement.setPriority(Integer.valueOf(vo.getPriority()));
		requirement.setTitle(vo.getTitle());
		requirement.setGameId(Long.valueOf(vo.getGameId()));
		requirement.setDetail(vo.getDetail());
		requirement.setEndTime(DateUtils.stringToDate(vo.getEndTime(),DateUtils.YYYY_MM_DD_HH_MM_SS));

		if (StringUtils.isNotBlank(vo.getSellingPointId())) {
			requirement.setSellingPointId(Long.valueOf(vo.getSellingPointId()));
		}
		if (StringUtils.isNotBlank(vo.getRemark())){
			requirement.setRemark(vo.getRemark());
		}
		// 1：文件 , 2：链接
		requirement.setFileType(Integer.valueOf(vo.getFileType()));
		if (DesignFileTypeEnum.FILE.getKey().equals(vo.getFileType())){
			if (Objects.nonNull(vo.getReferenceFile())){
				// 上传参考文件
				uploadFile(vo,requirement);
			}
		} else if (DesignFileTypeEnum.LINK.getKey().equals(vo.getFileType())){
			requirement.setFileLink(vo.getFileLink());
		}
		int flag = 0;
		if (StringUtils.isNotBlank(vo.getId())){
			requirement.setId(Long.valueOf(vo.getId()));
			requirement.setStatus(1);
			requirement.setUpdateTime(new Date());
			requirement.setUpdateId(Long.valueOf(SecurityUtils.getUser().getId()));
			// 修改信息
			flag = designRequirementMapper.updateById(requirement);
		}else{
			requirement.setCreateId(Long.valueOf(SecurityUtils.getUser().getId()));
			requirement.setPublishTime(new Date());
			// 保存信息
			flag = designRequirementMapper.insert(requirement);
		}
		if (flag > 0){
			// 更新制作人
			updateProducer(vo,requirement);
			// 更新标签
			updateLabel(vo,requirement);
		}
		return R.ok(requirement);
	}
	/**
	 * 需求操作記錄
	 * @param vo
	 * @return
	 */
	@Override
	public R getRecordList(DesignRequirementVo vo){
		QueryWrapper<DesignRequirementHistory> wrapper = new QueryWrapper<>();
		wrapper.eq("requirement_id",vo.getId());
		wrapper.eq("type",1);
		wrapper.eq("is_deleted",0);
		wrapper.orderByDesc("create_time");
		List<DesignRequirementHistory> designRequirementHistoryList = designRequirementHistoryMapper.selectList(wrapper);
		return R.ok(designRequirementHistoryList);
	}
	/**
	 * 更新需求状态
	 * @param vo
	 * @return
	 */
	@Override
	public R editNeedStatus(DesignRequirementVo vo){
		DesignRequirement requirement = designRequirementMapper.selectById(vo.getId());
		if (Objects.isNull(requirement)){
			return R.failed("需求唯一ID无效");
		}
		if (StringUtils.isNotBlank(vo.getStatus())){
			requirement.setStatus(Integer.valueOf(vo.getStatus()));
		}
		// 驳回原因
		if (StringUtils.isNotBlank(vo.getForbidReason())){
			requirement.setForbidReason(vo.getForbidReason());
		}
		// 卖点
		if (StringUtils.isNotBlank(vo.getSellingPointId())){
			requirement.setSellingPointId(Long.valueOf(vo.getSellingPointId()));
		}
		// 标签
		if (StringUtils.isNotBlank(vo.getLabelName())){
			// 更新标签
			updateLabel(vo,requirement);
		}
		// 转UE4
		if (StringUtils.equals(DesignEnum.DESIGN_TYPE_2.getKey().toString(),vo.getType())){
			requirement.setType(Integer.valueOf(vo.getType()));
			requirement.setDuration(vo.getDuration());
			requirement.setStatus(3);
			// 添加制作人
			editProducer(vo);
		}
		if (StringUtils.equals("3",vo.getStatus())){
			// 添加制作人
			editProducer(vo);
		}
		designRequirementMapper.updateById(requirement);
		return R.ok(requirement);
	}
	/**
	 * 提交成果
	 * @param vo
	 * @return
	 */
	@Override
	public R submitResult(DesignMaterialVo vo) {
		try {
			DesignRequirement requirement = designRequirementMapper.selectById(vo.getId());
			if (Objects.isNull(requirement)){
				return R.failed("需求唯一ID无效");
			}
			// 提交素材到盘古
			AdMaterialVo adMaterial = new AdMaterialVo();
			adMaterial.setFiles(vo.getResultFile());
			adMaterial.setNames(vo.getFileName());
			adMaterial.setMainGameId(String.valueOf(requirement.getGameId()));
			adMaterial.setCreatorId(String.valueOf(requirement.getCreateId()));
			adMaterial.setMakerId(String.valueOf(SecurityUtils.getUser().getId()));
			adMaterial.setMakeType("1");
			adMaterial.setUserId(String.valueOf(SecurityUtils.getUser().getId()));
			adMaterial.setSellingPointId(requirement.getSellingPointId().intValue());
			adMaterial.setOrigin(1);
			adMaterial.setOriginId(requirement.getId().intValue());
			// 内部调用推送到盘古
			R result = remoteAdMaterialService.addYanDiMaterial(adMaterial,SecurityConstants.FROM_IN);
			log.info(">>>提交素材到盘古result：{}",JSON.toJSONString(result));
			if (Objects.nonNull(result) && 0 == result.getCode() && Objects.nonNull(result.getData())){
				JSONArray array = JSON.parseArray(JSON.toJSONString(result.getData()));
				if (Objects.nonNull(array) && array.size() > 0){
					AdMaterial resMaterial = JSONObject.parseObject(JSON.toJSONString(array.get(0)),AdMaterial.class);
					requirement.setPanguMaterialId(resMaterial.getId());
					requirement.setResultLink(resMaterial.getFileUrl());
					requirement.setResultCoveLink(resMaterial.getImageUrl());
				}
			}else{
				return result;
			}
			requirement.setStatus(5);
			requirement.setCompleteTime(new Date());
			requirement.setResultProducerId(Long.valueOf(SecurityUtils.getUser().getId()));
			requirement.setUpdateId(Long.valueOf(SecurityUtils.getUser().getId()));
			// 更新数据
			designRequirementMapper.updateById(requirement);
			return R.ok(requirement);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return R.failed();
	}
	/**
	 * 标记
	 * @param vo
	 * @return
	 */
	@Override
	public R mark(DesignRequirementVo vo){
		DesignRequirement requirement = designRequirementMapper.selectById(vo.getId());
		if (Objects.isNull(requirement)){
			return R.failed("需求唯一ID无效");
		}
		requirement.setMarkStatus(2);
		designRequirementMapper.updateById(requirement);
		// 标记
		if (Objects.nonNull(vo.getProducerJson())){
			JSONArray array = vo.getProducerJson();
			for (Object object : array){
				JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(object));
				String id = String.valueOf(jsonObject.get("id"));
				String creativeRemark = String.valueOf(jsonObject.get("creativeRemark"));
				String prominentRemark = String.valueOf(jsonObject.get("prominentRemark"));

				DesignRequirementProducer designRequirementProducer = new DesignRequirementProducer();
				designRequirementProducer.setId(Long.valueOf(id));
				if (StringUtils.isNotBlank(creativeRemark) && !StringUtils.equals("null",creativeRemark)){
					designRequirementProducer.setCreativeRemark(Integer.valueOf(creativeRemark));
				}
				if (StringUtils.isNotBlank(prominentRemark) && !StringUtils.equals("null",prominentRemark)){
					designRequirementProducer.setProminentRemark(Integer.valueOf(prominentRemark));
				}
				designRequirementProducerMapper.updateById(designRequirementProducer);
			}
		}
		return R.ok(requirement);
	}
	/**
	 * 更新制作人
	 * @param vo
	 * @return
	 */
	public void editProducer(DesignRequirementVo vo){
		// 清空制作人
		QueryWrapper<DesignRequirementProducer> wrapper = new QueryWrapper<>();
		wrapper.eq("requirement_id",vo.getId());
		designRequirementProducerMapper.delete(wrapper);
		if (Objects.nonNull(vo.getProducerJson())){
			JSONArray array = vo.getProducerJson();
			if (Objects.nonNull(array)){
				for (Object object : array){
					JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(object));
					String producerId = jsonObject.getString("producerId");
					String producerValue = jsonObject.getString("producerValue");
					String producerType = jsonObject.getString("producerType");

					DesignRequirementProducer designRequirementProducer = new DesignRequirementProducer();
					designRequirementProducer.setRequirementId(Long.valueOf(vo.getId()));
					if (StringUtils.isNotBlank(producerId)){
						designRequirementProducer.setProducerId(Long.valueOf(producerId));
					}
					if (StringUtils.isNotBlank(producerValue)){
						designRequirementProducer.setProducerValue(producerValue);
					}
					if (StringUtils.isNotBlank(producerType)){
						designRequirementProducer.setProducerType(Integer.valueOf(producerType));
					}
					designRequirementProducer.setCreateId(Long.valueOf(SecurityUtils.getUser().getId()));
					designRequirementProducerMapper.insert(designRequirementProducer);
				}
			}

		}
	}
	/**
	 * 上传文件
	 * @param vo
	 * @param requirement
	 */
	public void uploadFile(DesignRequirementVo vo,DesignRequirement requirement){
		try {
			MultipartFile file = vo.getReferenceFile();
			String fileName = file.getOriginalFilename();
			String suffix = fileName.substring(fileName.lastIndexOf(com.pig4cloud.pig.api.util.Constants.POINT) + 1).toLowerCase();
			// 视频文件 获取 封面地址
			if (StringUtils.equals("mp4",suffix)){
				String upPath = yandiProperties.getUploadPath() + DateUtils.dateToString(new Date(), DateUtils.YYYYMMDD) + "/";
				String downUrl = yandiProperties.getDownloadUrl() + DateUtils.dateToString(new Date(), DateUtils.YYYYMMDD) + "/";
				Map<String, Object> resultMap = UploadUtils.videoUpload(file, upPath, Long.parseLong(yandiProperties.getSize()));
				if (Objects.nonNull(resultMap) && 0 == Integer.parseInt(String.valueOf(resultMap.get("code")))) {
					//访问url
					requirement.setFileLink(downUrl + resultMap.get("filename"));
					// 保存封面
					if (Objects.nonNull(resultMap.get("videoImgList"))) {
						List<Map<String, Object>> videoImgList = (List<Map<String, Object>>) resultMap.get("videoImgList");
						requirement.setFileCoverLink(downUrl + videoImgList.get(0).get("imageName"));
					}
				}
			}else{
				String md5 = DigestUtils.md5Hex(file.getInputStream());
				String objectName = md5 + "." + suffix;
				minioTemplate.putObject(Constants.AD_MATERIAL,objectName,file.getInputStream());
				String fileUrl = yandiProperties.getMinioFilePrefixUrl() + "/" + Constants.AD_MATERIAL + "/" + objectName;
				requirement.setFileLink(fileUrl);
				requirement.setFileCoverLink(fileUrl);
			}
		} catch (Exception e){
			e.printStackTrace();
		}

	}
	/**
	 * 更新制作人
	 * @param vo
	 * @param requirement
	 */
	public void updateProducer(DesignRequirementVo vo,DesignRequirement requirement){
		if (StringUtils.isNotBlank(vo.getId())) {
			// 清空制作人
			QueryWrapper<DesignRequirementProducer> wrapper = new QueryWrapper<>();
			wrapper.eq("requirement_id",requirement.getId());
			designRequirementProducerMapper.delete(wrapper);
		}
		if (StringUtils.isNotBlank(vo.getProducerId())){
			// 添加制作人
			DesignRequirementProducer designRequirementProducer = new DesignRequirementProducer();
			designRequirementProducer.setRequirementId(requirement.getId());
			designRequirementProducer.setProducerId(Long.valueOf(vo.getProducerId()));
			designRequirementProducer.setCreateId(Long.valueOf(SecurityUtils.getUser().getId()));
			designRequirementProducerMapper.insert(designRequirementProducer);
		}
	}

	/**
	 * 根据需求类型查询对应制作人列表
	 * @param vo
	 * @return
	 */
	@Override
	public R getProducerListByType(DesignRequirementVo vo){
		Map<String,Object> param = new HashMap<>();
		param.put("tenantId", TenantContextHolder.getTenantId());
		param.put("type",vo.getType());
		List<Map<String,Object>> resultMap = designRequirementMapper.selectProducerList(param);
		return R.ok(resultMap);
	}
	/**
	 * 待审核需求总数
	 * @return
	 */
	@Override
	public R auditTotal(){
		boolean isManager = dataChartService.isDesignManager();
		if (!isManager){
			return R.ok(0);
		}
		QueryWrapper<DesignRequirement> wrapper = new QueryWrapper<>();
		wrapper.in("status",1,5);
		wrapper.eq("mark_status",1);
		wrapper.eq("is_deleted",0);
		int count = designRequirementMapper.selectCount(wrapper);
		return R.ok(count);
	}
	/**
	 * 更新标签
	 * @param vo
	 * @param requirement
	 */
	public void updateLabel(DesignRequirementVo vo,DesignRequirement requirement){
		if (StringUtils.isNotBlank(vo.getId())) {
			// 清空标签
			QueryWrapper<AdLabelRelate> wrapper = new QueryWrapper<>();
			wrapper.eq("relate_id", vo.getId());
			wrapper.eq("type", 3);
			wrapper.eq("is_delete", 0);
			adLabelRelateMapper.delete(wrapper);
		}
		if (StringUtils.isNotBlank(vo.getLabelName())){
			// 添加标签
			String[] labelIds = vo.getLabelName().split(",");
			for (String labelId : labelIds){
				AdLabelRelate adLabelRelate = new AdLabelRelate();
				adLabelRelate.setLabelId(Integer.valueOf(labelId));
				adLabelRelate.setRelateId(requirement.getId().intValue());
				adLabelRelate.setType(3);
				adLabelRelate.setCreateTime(new Date());
				adLabelRelate.setUpdateTime(new Date());
				adLabelRelateMapper.insert(adLabelRelate);
			}
		}
	}
	/**
	 * 处理列表数据
	 * @param list
	 */
	public void dealData(List<DesignRequirementDto> list){
		if (Objects.nonNull(list) && list.size() > 0) {
			Collection<Long> gameIds = list.stream().map(item -> {
				return Long.valueOf(String.valueOf(item.getGameId()));
			}).collect(Collectors.toSet());
			// 获取父游戏列表
			R<List<ParentGameDO>> gameListData = remotePGameService.getCacheablePGameList(new ParentGameReq().setIds(gameIds));
			List<ParentGameDO> gameList = gameListData.getData();

			for (DesignRequirementDto requirement : list) {
				// 翻译父游戏名称
				if (Objects.nonNull(gameList) && gameList.size() > 0) {
					gameList.forEach(game -> {
						if (requirement.getGameId().intValue() == game.getId().intValue()) {
							requirement.setGameName(game.getGname());
						}
					});
				}

				// 查询需求对应制作者列表
				DesignRequirementProducerVo designRequirementProducerVo = new DesignRequirementProducerVo();
				designRequirementProducerVo.setRequirementId(String.valueOf(requirement.getId()));
				requirement.setProducerList(designRequirementProducerMapper.selectByList(designRequirementProducerVo));
			}
		}
	}

}


